package jp.tkym.labs.rpc;

import java.net.URL;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;

class RpcJettyServer{
	private final Server server;
	private final ServletContextHandler servletContextHandler = new ServletContextHandler();

	RpcJettyServer(){
		this(80);
	}
	
	RpcJettyServer(int port){
		this(port, "html");
	}
	
	RpcJettyServer(int port, String resouceFolder){
		server = new Server(port);
		HandlerList handlerList = new HandlerList();
		handlerList.addHandler(createResourceHandler(resouceFolder));
		handlerList.addHandler(servletContextHandler);
		server.setHandler(handlerList);
	}
	
	private ResourceHandler createResourceHandler(String folderName){
		ResourceHandler resourceHandler = new ResourceHandler();
		String path = resourceBaseOf(folderName);
		resourceHandler.setResourceBase(path);
		return resourceHandler; 
	}
	
	private String resourceBaseOf(String folderName){
		URL resourceUrl = RpcJettyServer.class.getResource(folderName);
		return resourceUrl.toExternalForm();
	}
	
	final ServletContextHandler getServletContextHandler(){
		return servletContextHandler;
	}
	
	@Override
	protected void finalize() throws Throwable {
		stop();
		super.finalize();
	}
	
	void stop() throws Exception{
		if(server != null)
			server.stop();
	}
	
	void start() throws Exception {
		server.start();
	}

	public static void main(String[] args) {
		try {
			new RpcJettyServer().start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}